package linhnv.app;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.net.Uri;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;

public class GIFView extends View{
	
	private static Movie movie;
	//InputStream is = null;
	long moviestart = 0;
	public GIFView(Context context) {
		super(context);
	}
	public GIFView(Context context, AttributeSet set) {
		super(context, set);
		
		if(movie == null)
		{
//			byte[] arr = getImageBitmap();
//			if(arr == null)
//			{
//				movie = null;
//			}
//			else
//			{
//				movie = Movie.decodeByteArray(arr, 0, arr.length);
//			}
//			InputStream is = context.getResources().openRawResource(R.drawable.animated_gif);
//			movie = Movie.decodeStream(is);
		}
	}
	@Override
	protected void onDraw(Canvas canvas) {
		if(movie == null)
		{
			return;
		}
		canvas.drawColor(0xFFCCCCCC);
		super.onDraw(canvas);
		long now = android.os.SystemClock.uptimeMillis();
		//System.out.println("now=" + now);
		 if (moviestart == 0) {   // first time
             moviestart = now;
             
         }
		 //System.out.println("\tmoviestart="+moviestart);
		 int relTime = (int)((now - moviestart) % 1000/*movie.duration()*/) ;
		 //System.out.println("time="+relTime+"\treltime="+movie.duration());
         movie.setTime(relTime);
         movie.draw(canvas, 0, 0);
         this.invalidate();
	}
	
	public byte[] getImageBitmap() { 
		byte[] imageRaw = null;
		  try {
		     URL url = new URL("http://kenhgiaiphap.vn/quangcao/quangcao01.gif");
		     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
		     urlConnection.setRequestMethod("GET");
		     urlConnection.setDoOutput(true);
		     urlConnection.connect();
		     
		     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
		     
		     ByteArrayOutputStream out = new ByteArrayOutputStream();

//		     int c;
//		     while ((c = in.read()) != -1) {
//		         out.write(c);
//		     }
//		     out.flush();
		     
		     int bufferSize = 1024;
		     byte[] buffer = new byte[bufferSize];

		     // we need to know how may bytes were read to write them to the byteBuffer
		     int len = 0;
		     while ((len = in.read(buffer)) != -1) {
		       out.write(buffer, 0, len);
		     }
		     out.flush();
		     imageRaw = out.toByteArray();
		     urlConnection.disconnect();
		     in.close();
		     out.close();
		  } catch (IOException e) {
			  
		     // TODO Auto-generated catch block
		     e.printStackTrace();
		     imageRaw = null;
		  }

       return imageRaw; 
    } 
}